package com.menggudf.dao;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import com.menggudf.entity.User;

@Repository
public class UserDao {

    private static final Log log = LogFactory.getLog(UserDao.class);

    @PersistenceContext(unitName = "medicalUnit")
    private EntityManager entityManager;

    public void persist(User transientInstance) {
        try {
            entityManager.persist(transientInstance);
        } catch (RuntimeException re) {
            log.error("persist failed", re);
            throw re;
        }
    }

    public void remove(User persistentInstance) {
        try {
            entityManager.remove(persistentInstance);
        } catch (RuntimeException re) {
            log.error("remove failed", re);
            throw re;
        }
    }

    public User merge(User detachedInstance) {
        try {
            User result = entityManager.merge(detachedInstance);
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    public User findById(Long id) {
        try {
            User instance = entityManager.find(User.class, id);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }

    public User findByPhone(String phone) {
        try {
            StringBuffer sqld = new StringBuffer("from User u where u.phone=?1 ");
            Query query = entityManager.createQuery(sqld.toString()).setParameter(1, phone);
            List<User> list = query.getResultList();
            if(list!=null && list.size()>0){
                return list.get(0);
            }else{
                return null;
            }
        } catch (Exception e) {
            log.error("findByPhone fail",e);
            throw e;
        }
    }

    public List<User> getUserList(
            String userCode,
            String userName,
            int pageSize,
            int offset,
            Date startTime,
            Date endTime) {
        try {
            StringBuffer sqld = new StringBuffer("from User u where u.createTime>=?1 and u.createTime<=?2 ");
            int num = 2;
            if(!StringUtils.isEmpty(userCode)){
                sqld.append(" and u.userCode=?"+(++num));
            }
            if(!StringUtils.isEmpty(userName)){
                sqld.append(" and u.userName=?"+(++num));
            }
            sqld.append(" order by u.createTime desc ");
            Query query = entityManager.createQuery(sqld.toString());
            num = 2;
            if(!StringUtils.isEmpty(userCode)){
                query.setParameter(++num, userCode);
            }
            if(!StringUtils.isEmpty(userName)){
                query.setParameter(++num, userName);
            }
            query.setFirstResult(offset).setMaxResults(pageSize);
            query.setParameter(1, startTime).setParameter(2, endTime);
            return query.getResultList();
        } catch (Exception e) {
            log.error("getUserList fail",e);
            throw e;
        }
    }
    
    public long getUserListCount(
            String userCode,
            String userName,
            Date startTime,
            Date endTime) {
        try {
            StringBuffer sqld = new StringBuffer("select count(*) from User u where u.createTime>=?1 and u.createTime<=?2 ");
            int num = 2;
            if(!StringUtils.isEmpty(userCode)){
                sqld.append(" and u.userCode=?"+(++num));
            }
            if(!StringUtils.isEmpty(userName)){
                sqld.append(" and u.userName=?"+(++num));
            }
            Query query = entityManager.createQuery(sqld.toString());
            num = 2;
            if(!StringUtils.isEmpty(userCode)){
                query.setParameter(++num, userCode);
            }
            if(!StringUtils.isEmpty(userName)){
                query.setParameter(++num, userName);
            }
            query.setParameter(1, startTime).setParameter(2, endTime);
            return (long) query.getSingleResult();
        } catch (Exception e) {
            log.error("getUserListCount fail",e);
            throw e;
        }
    }

    public User findByUserCode(String primaryRole) {
        try {
            StringBuffer sqld = new StringBuffer("from User u where u.userCode=?1 ");
            Query query = entityManager.createQuery(sqld.toString()).setParameter(1, primaryRole);
            List<User> list = query.getResultList();
            if(list!=null && list.size()>0){
                return list.get(0);
            }else{
                return null;
            }
        } catch (Exception e) {
            log.error("findByUserCode fail",e);
            throw e;
        }
    }

    public User getUserDetail(String userCode) {
        try {
            StringBuffer sqld = new StringBuffer("from User u where u.userCode=?1 ");
            Query query = entityManager.createQuery(sqld.toString()).setParameter(1, userCode);
            List<User> list = query.getResultList();
            if(list!=null && list.size()>0){
                return list.get(0);
            }else{
                return null;
            }
        } catch (Exception e) {
            log.error("getUserDetail fail",e);
            throw e;
        }
    }
}
